/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:BeanCopyUtils.java
 *    Date:2023/11/18 下午11:45
 *    Author:赵士杰
 */

package com.hw.common.utils.bean;

import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Project：hello-world
 * @ClassName BeanCopyUtils
 * @Description Bean对象属性拷贝
 * @Author：Jie
 * @Date：2023/10/21 20:07
 */
public class BeanCopyUtils {

    public BeanCopyUtils() {}

    public static <V> V copyBean(Object source,Class<V> clazz) {
        //创建目标对象
        try {
            V result = clazz.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("Failed to copy bean properties", e);
        }
    }

    public static <O,V> List<V>  copyBeanList(List<O> list, Class<V> clazz) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        //stream流，函数式编程
        return list.stream()
                .map(o -> copyBean(o,clazz))
                .collect(Collectors.toList());
    }

}